package com.lsh.service.impl;

import com.lsh.dao.UserDao;
import com.lsh.dao.UserDatumDao;
import com.lsh.dao.UserHeadPortraitDao;
import com.lsh.dao.UserTokenDao;
import com.lsh.domain.UserDatum;
import com.lsh.exception.SysException;
import com.lsh.service.IndexService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@CacheConfig(cacheNames = "auth_token")
public class IndexServiceImpl implements IndexService {

    @Autowired
    UserDao userDao;
    @Autowired
    UserTokenDao userTokenDao;
    @Autowired
    UserDatumDao userDatumDao;
    @Autowired
    UserHeadPortraitDao userHeadPortraitDao;

    /**
     * 检查用户状态并获取用户ID
     * @param token
     * @return
     */
    @Override
    @Cacheable(key = "'id_' + #token")
    public String findByUserId(String token) {
        String userId = userTokenDao.getByToken(token);
        return userId;
    }

    /**
     * 根据token直接获取当前用户昵称
     * @param token
     * @return
     */
    public String findNickname(String token){
        String userId = userTokenDao.getByToken(token);
        String nickname = userDatumDao.getNickname(Integer.parseInt(userId));
        return nickname;
    }

    /**
     * 获取用户所有展示的信息
     * @param userId
     * @return
     */
    @Override
    public Map<String, String> showUser(Integer userId) {
        UserDatum  userDatum= userDatumDao.getByUserId(userId);
        String headPortrait = userHeadPortraitDao.getURL(userId);
        String[] address = userDatum.getAddress().split(" ");
        Map map = new HashMap();
        map.put("nickName", userDatum.getNickname());
        if(address.length == 2){
            map.put("province", address[0]);
            map.put("city", address[1]);
        }else{
            map.put("province", "");
            map.put("city", "");
        }
        map.put("headPortrait", headPortrait);
        return map;
    }

    /**
     * 退出登录
     * @param token
     */
    @Override
    @CacheEvict(key = "'id_' + #token")
    public void logoutUser(String token) throws SysException {
        int result = userTokenDao.updateUserStatus(token);
        if(result == 0) throw new SysException("退出登录失败");
    }


}
